package com.kun.portal.webframe.service;

import com.kun.portal.webframe.dao.RoomDao;
import com.kun.portal.webframe.po.AppointmentPo;
import com.kun.portal.webframe.po.RoomPo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/5/4.
 */
@Service
public class RoomService {
    @Autowired
    private RoomDao roomDao;
    @Autowired
    private EntityManager entityManager;
    public RoomPo saveRoom(RoomPo appo) {
        return (RoomPo)this.roomDao.save(appo);
    }
    public void deleteRoom(RoomPo room) {
         Query query = entityManager.createQuery("select f from SignInPo f where f.room.roomId  = :roomId ");
        query.setParameter("roomId",room.getRoomId());
        query.setMaxResults(1);
        List list = query.getResultList();
        if(list.size()==0){
            this.roomDao.delete(room);
        }else{
            room.setEffective(false);
            roomDao.save(room);
        }


    }
    public List<RoomPo> getAllRooms(String fileter){

            Specification query = new Specification<AppointmentPo>() {
                @Override
                public Predicate toPredicate(Root<AppointmentPo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                    Predicate effective = cb.equal(root.get("effective"),true);
                    if(StringUtils.isNoneBlank(fileter)){
                        List<Predicate> predicates = new ArrayList<>();

                            predicates.add(cb.like(root.get("roomName"), "%"+fileter+"%"));
                            predicates.add(cb.like(root.get("roomNum"), "%"+fileter+"%"));

                        Predicate predicate = cb.or(predicates.toArray(new Predicate[predicates.size()]));
                        return  query.where(effective,predicate).getRestriction();
                    }
                    return effective;
                }
            };
            return this.roomDao.findAll(query);


    }
}
